package com.dana.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.domain.TableDataInfo;
import com.core.enums.ResultCode;
import com.dana.friend.domain.question.Question;
import com.dana.friend.domain.question.dto.QuestionQueryDTO;
import com.dana.friend.domain.question.es.QuestionES;
import com.dana.friend.domain.question.vo.QuestionDetailVO;
import com.dana.friend.domain.question.vo.QuestionVO;
import com.dana.friend.elasticsearch.QuestionRepository;
import com.dana.friend.manager.QuestionCacheManager;
import com.dana.friend.mapper.question.QuestionMapper;
import com.dana.friend.service.question.IQuestionService;
import com.dana.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionCacheManager questionCacheManager;
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        //es中没有题目数据就去数据获取并存储到es中
        if (questionRepository.count() <= 0) {
            refreshQuestion();
        }
        //判断搜索条件
        String keyword = questionQueryDTO.getKeyword();
        Integer difficulty = questionQueryDTO.getDifficulty();
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable= PageRequest.of(questionQueryDTO.getPageNum()-1, questionQueryDTO.getPageSize(),sort);
        Page<QuestionES> questionESPage;
        if (difficulty==null&& StrUtil.isEmpty(keyword)){//全部为空
            questionESPage = questionRepository.findAll(pageable);
        }else if (difficulty==null){//题目难度为空
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        }else if (StrUtil.isEmpty(keyword)){//关键字为空
            questionESPage =questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }else {//全部不为空
            questionESPage =questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }

        long total = questionESPage.getTotalElements();
        if (total==0){
            return TableDataInfo.empty();
        }
        //获取正文信息
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList= BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList,total);
    }

    /**
     * 获取题目详情
     * @param questionId 题目id
     * @return 题目信息
     */
    @Override
    public QuestionDetailVO detail(Long questionId) {
        //先去es中查询,不存在就去查询数据库并且刷新es
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO=new QuestionDetailVO();
        if (questionES!=null){
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        Question question = questionMapper.selectById(questionId);
        if (question==null){
            throw new ServiceException(ResultCode.QUESTION_NOT_EXISTS);
        }
        //刷新es
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    /**
     * 获取上一题
     * 借助redis的list结构进行存储,首先判断缓存内有没有
     * 有就直接返回,没有就查询数据库并且更新缓存
     *
     * @param questionId
     * @return
     */
    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
       return questionCacheManager.preQuestion(questionId).toString();
    }

    /**
     * 获取下一题
     * 借助redis的list结构进行存储
     * @param questionId
     * @return
     */
    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }


    /**
     * 刷新es数据
     */
    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
